package com.hjx.windowtool.mi;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JSplitPane;

import com.hjx.windowtool.util.WinUtil;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinUser.WINDOWINFO;

import java.awt.AWTException;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;

import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class MiQianggouApp {

	private static final int chromeLocationY = 40;
	private JFrame frame;
	private JTextField txt_userName;
	private JPasswordField txt_password;
	private Panel panel_1;
	private JTextField txt_times;
	private HWND hwnd;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					MiQianggouApp window = new MiQianggouApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MiQianggouApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("小米");
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.5);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		frame.addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(WindowEvent e) {
				System.out.println("windowOpened=" + e);
			}

			@Override
			public void windowIconified(WindowEvent e) {
				System.out.println("windowIconified=" + e);
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				System.out.println("windowDeiconified=" + e);
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				System.out.println("windowDeactivated=" + e);
				// frame.setVisible(false);
			}

			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("windowClosing=" + e);
			}

			@Override
			public void windowClosed(WindowEvent e) {
				System.out.println("windowClosed=" + e);
			}

			@Override
			public void windowActivated(WindowEvent e) {
				System.out.println("windowActivated=" + e);
			}
		});

		JPanel panel = new JPanel();
		splitPane.setLeftComponent(panel);
		panel.setLayout(null);

		JLabel label = new JLabel("用戶名");
		label.setBounds(10, 10, 54, 15);
		panel.add(label);

		txt_userName = new JTextField();
		txt_userName.setBounds(63, 7, 159, 21);
		panel.add(txt_userName);
		txt_userName.setColumns(10);

		JLabel label_1 = new JLabel("密  码");
		label_1.setBounds(10, 35, 38, 15);
		panel.add(label_1);

		JButton button = new JButton("抢购");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WinUtil.loginMi(txt_userName.getText(), new String(txt_password.getPassword()));
				Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
					@Override
					public void run() {
						try {
							System.out.println("当前时间："+WinUtil.formatDate(new Date()));
							List<Date> list = getTimes();
							boolean isWillBegin = false;
							Date stopTime = new Date();
							for (Date date : list) {
								if (new Date().after(new Date(date.getTime() - 95000)) && new Date().before(new Date(date.getTime() + 5000))) {
									isWillBegin = true;
									stopTime = new Date(date.getTime() + 15000);
									break;
								}
							}
							if (!isWillBegin) {
								return;
							}
							List<WebElement> miPayElement = getMiPayElement(WinUtil.getChromeDriver());
							for (WebElement webElement : miPayElement) {
								System.out.println(webElement.getText());
								if (webElement.getText().contains("提醒")) {
									return;
								}
								if (webElement.getText().contains("登录后")) {
									webElement.click();
									miPayElement = getMiPayElement(WinUtil.getChromeDriver());
									break;
								}
							}
							System.out.println(WinUtil.formatDate(new Date()) + "===" + WinUtil.formatDate(stopTime));
							while (new Date().before(stopTime)) {
								try {
									for (WebElement webElement : miPayElement) {
										webElement.click();
									}
								} catch (Throwable e) {
									miPayElement = getMiPayElement(WinUtil.getChromeDriver());
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}, 1, 30, TimeUnit.SECONDS);
				button.setEnabled(false);
			}
		});
		button.setBounds(63, 80, 93, 23);
		panel.add(button);

		txt_password = new JPasswordField();
		txt_password.setBounds(63, 32, 159, 21);
		panel.add(txt_password);

		JLabel label_2 = new JLabel("时  间");
		label_2.setBounds(10, 60, 54, 15);
		panel.add(label_2);

		txt_times = new JTextField();
		txt_times.setText("00:00;10:00;12:00;18:00;20:00;22:00");
		txt_times.setBounds(63, 57, 359, 21);
		panel.add(txt_times);
		txt_times.setColumns(10);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		splitPane.setRightComponent(scrollPane);

		panel_1 = new Panel();
		panel_1.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				if(hwnd==null) {
					return;
				}
				Rectangle r=panel_1.getBounds();
				User32.INSTANCE.SetWindowPos(hwnd, null, 0, -chromeLocationY, r.width, r.height+chromeLocationY, User32.SWP_NOZORDER);
			}
		});
		splitPane.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				double value = 100d / splitPane.getBounds().getHeight();
				double doubleValue = new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).doubleValue();
				System.out.println(panel_1.getBounds() + "==" + splitPane.getBounds()+"=="+value+"=="+doubleValue);
				splitPane.setResizeWeight(value);
				splitPane.repaint();
				splitPane.getParent().repaint();
			}
		});
		scrollPane.setViewportView(panel_1);
		init();
	}

	protected List<Date> getTimes() {
		List<Date> list = new ArrayList<>();
		String text = txt_times.getText();
		String[] split = text.split(";");
		Calendar c = Calendar.getInstance();
		for (String string : split) {
			String[] split2 = string.split(":");
			if (split2.length != 2) {
				continue;
			}
			c.setTime(new Date());
			c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(split2[0]));
			c.set(Calendar.MINUTE, Integer.valueOf(split2[1]));
			c.set(Calendar.SECOND, 0);
			c.set(Calendar.MILLISECOND, 0);
			if (Integer.valueOf(split2[0]) == 0) {
				c.add(Calendar.DAY_OF_MONTH, 1);
			}
			System.out.println(WinUtil.formatDate(c.getTime()));
			list.add(c.getTime());
		}
		return list;
	}

	public static List<WebElement> getMiPayElement(ChromeDriver d) {
		List<WebElement> list = new ArrayList<>();
		d.get("https://www.mi.com/seckill/");
		List<WebElement> webElements = d.findElementsByTagName("ul");
		for (int i = 0; i < webElements.size(); i++) {
			WebElement webElement = webElements.get(i);
			List<WebElement> findElements = webElement.findElements(By.tagName("li"));
			if (webElement.getText().contains("元") && findElements.size() > 10) {
				// System.out.println(webElement.getText());
				for (WebElement webElement2 : findElements) {
					WebElement findElement2 = webElement2.findElement(By.className("price"));
					String text = findElement2.getText();
					String[] split = text.trim().split("元");
					Double minPrice = Double.valueOf(split[0].trim());
					Double maxPrice = Double.valueOf(split[1].trim());
					System.out.println(split[0] + "==" + split[1]);
					System.out.println(text);
					if (maxPrice / minPrice <= 10) {
						continue;
					}
					WebElement findElement = webElement2.findElement(By.className("btn"));
					System.out.println("====" + findElement.getText());
					list.add(findElement);
				}
			}
		}
		return list;
	}

	private void init() {
		try {
			SystemTray systemTray = SystemTray.getSystemTray();
			String filename = null;
			TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(filename));
			trayIcon.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					frame.setVisible(!frame.isVisible());
				}
			});
			systemTray.add(trayIcon);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		new Thread(new Runnable() {

			public void run() {
				try {
					Runtime.getRuntime().exec("taskkill /f /im chrome.exe");
					ChromeDriver d = WinUtil.getChromeDriver();
					User32 user32 = User32.INSTANCE;
					hwnd = null;
					hwnd = user32.FindWindowEx(null, hwnd, "Chrome_WidgetWin_1", null);
					hwnd = user32.FindWindowEx(null, hwnd, "Chrome_WidgetWin_1", null);
					char[] lpString = new char[user32.GetWindowTextLength(hwnd)];
					user32.GetWindowText(hwnd, lpString, lpString.length);
					System.out.println(hwnd + "==" + new String(lpString));
					int oldStyle = user32.GetWindowLong(hwnd, User32.GWL_STYLE);
					user32.SetWindowLong(hwnd, User32.GWL_STYLE, oldStyle & ~User32.WS_BORDER);
					user32.SetParent(hwnd, new HWND(Native.getComponentPointer(panel_1)));
					Rectangle r=panel_1.getBounds();
					user32.SetWindowPos(hwnd, null, 0, -chromeLocationY, r.width, r.height+chromeLocationY, User32.SWP_NOZORDER);
					// user32.setwind
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
